package com.hzya.frame.utils.core.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.hzya.frame.system.user.entity.UserEntity;
import com.hzya.frame.utils.core.entity.BaseEntity;

public class SessionContext {

	private static Log logger = LogFactory.getLog(SessionContext.class);

	private SessionContext() {
	}

	public static void putUser(UserEntity user) {
		WebContext.getSession().setMaxInactiveInterval(3 * 60 * 1000);
		WebContext.getSession().setAttribute("_CURRENT_USER", user);
	}

	public static void putImageNo(String image_no) {
		WebContext.getSession().setAttribute("image_no", image_no);
	}

	public static UserEntity getUser() {
		HttpSession session = WebContext.getSession();
		if (session != null)
			return (UserEntity) session.getAttribute("_CURRENT_USER");
		else
			return null;
	}

	public static void removeUser(UserEntity user) {
		WebContext.getSession().removeAttribute("_CURRENT_USER");
	}

	/**
	 * 获得当前登录用户
	 * 
	 * @return
	 */
	public static UserEntity getCurrentUser() {
		HttpServletRequest request = WebContext.getRequest();
		HttpServletResponse response = WebContext.getResponse();
		UserEntity ui = (UserEntity) request.getSession().getAttribute("_CURRENT_USER");
		if (ui == null) {
			try {
				response.sendRedirect(request.getContextPath() + "/login");
			} catch (Exception ex) {
				logger.info("redirect.......");
			}
			throw new RuntimeException("未登陆");
		}
		return ui;
	}

	/**
	 * 设置用户到session中
	 * 
	 * @param tempObj
	 * @return
	 */
	public static boolean setCurrentUser(BaseEntity tempObj) {
		HttpServletRequest request = WebContext.getRequest();
		boolean flag = true;
		request.getSession().setAttribute("_CURRENT_USER", tempObj);
		return flag;
	}

	/**
	 * 删除当前用户
	 * 
	 * @param tempObj
	 * @return
	 */
	public static boolean removeCurrentUser() {
		boolean flag = true;
		HttpServletRequest request = WebContext.getRequest();
		request.getSession().removeAttribute("_CURRENT_USER");
		return flag;
	}

}
